﻿using System;
using System.Collections.Generic;
using System.Linq;
using FPPrinter.Models.Doc;
using FPPrinter.Models.SourceFiles;

namespace FPPrinter.Models
{
    public class OptimizedDocManager : IOptimizedDocManager
    {
        public void GenerateDocs(IEnumerable<ISourceFile> sfs)
        {
            _docs.Clear();
            //1 短的发票2合1为一页，到新文档。制成打印方案：（单面，一键打印）
            //2 长发票打印最佳方案（双面，长翻转，一键打印）
            var sfss=sfs.Where(x => x .FileType== FileType.Short).ToList() ;
            var lfs=sfs.Where(x => x .FileType== FileType.Long).ToList() ;

            if (sfss.Any())
            {
                var sof = new ShortOptimizedDoc();
                sof.Generate(sfss.Select(x=>x.PagesImages.FirstOrDefault()));
                _docs.Add(sof);
                                
            }

            
     
            if (lfs.Any())
            {
                foreach (var lfile in lfs)
                {
                    var lf = new LongOptimizedDoc();
                    lf.Generate(lfile.PagesImages  );
                    _docs.Add(lf);
                }

            }
    
        


            RaiseChanged();
        }

        event EventHandler<IEnumerable<IOptimizedDoc>> _DocsChanged;
        public event EventHandler<IEnumerable<IOptimizedDoc>> DocsChanged
        {
            add
            {
                _DocsChanged += value;
                RaiseChanged();
            }
            remove { _DocsChanged -= value; }
        }

        private void RaiseChanged()
        {
            _DocsChanged?.Invoke(this,Docs);

            
        }


        List<IOptimizedDoc> _docs  = new List<IOptimizedDoc>();
        public  IEnumerable<IOptimizedDoc> Docs  => _docs;
        public void Clear()
        {
           
            _docs.Clear();
            RaiseChanged();
        }
    }
}